<template>
  <div>
    登录页面
    <div>
      <div>
        手机号 <input v-model="usertel" />
        <button v-if="disabled" :disabled="disabled">发送验证码</button>
        <button v-else @click="send">发送验证码</button>
      </div>
      <div>验证码 <input v-model="code" /></div>
    </div>

    <button @click="gotoMenu">登录</button>

    <hr />
    <button @click="showImg">点击扫码登录</button>
    <img v-if="imgsrc" :src="imgsrc" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { sentCode, verify, qrkey, qrcreate,qrcheck } from '../service/userService.tsx'
let $router = useRouter() //闭包 实例化

let usertel = ref()
let code = ref() //验证码
let disabled = ref(true) //不可用
let imgsrc = ref() //图片地址
let timer = ref()//定时器

let telReg = /^1[3-9][0-9]{9}$/

let showImg = async () => {//生成二维码
  let res = await qrkey({})
  let key = res.data.data.unikey //找到key

  let res2 = await qrcreate({
    key,
    qrimg:true
  })
  imgsrc.value = res2.data.data.qrimg;
  //判断二维码的扫码状态

  timer.value = setTimeout(async()=>{//延迟期
    let res3  = await  qrcheck({
      key
    })
    if(res3.data.code == 803){
       document.cookie  = res3.data.cookie;//存放cookie
       clearTimeout(timer.value);
       $router.push("/menu")
    }


  },8000);//两秒以后触发

  

}

let send = async () => {
  //发送的方法
  let res = await sentCode({
    phone: usertel.value,
    timestamp: Date.now()
  })
  console.log(res);
 
}
watch([usertel], () => {
  if (telReg.test(usertel.value)) {
    disabled.value = false
  } else {
    disabled.value = true
  }
})

let gotoMenu = async () => {
  let res = await verify({
    phone: usertel.value,
    captcha: code.value,
    timestamp: Date.now()
  })
  console.log(res)

   $router.push('/menu')
}
</script>
